package com.ai_daily.aitiantian.api;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.ai_daily.aitiantian.BuildConfig;
import com.ai_daily.aitiantian.Constants;
import com.ai_daily.aitiantian.KeywordRepository;
import com.ai_daily.aitiantian.bean.BaseResponseBean;
import com.ai_daily.aitiantian.bean.ChatStreamResponse;
import com.ai_daily.aitiantian.bean.CommonConfigResponseBean;
import com.ai_daily.aitiantian.bean.InitResponseBean;
import com.ai_daily.aitiantian.bean.QueryInfoResponseBean;
import com.ai_daily.aitiantian.bean.QueryVersionInfoResponseBean;
import com.ai_daily.aitiantian.bean.param.ChatParam;
import com.ai_daily.aitiantian.bean.param.CloseChatParam;
import com.ai_daily.aitiantian.bean.param.CommonConfigParam;
import com.ai_daily.aitiantian.bean.param.DeviceInfoParam;
import com.ai_daily.aitiantian.bean.param.QueryInfoParam;
import com.ai_daily.aitiantian.bean.param.QueryLogoParam;
import com.ai_daily.aitiantian.bean.param.QueryVersionInfoParam;
import com.ai_daily.aitiantian.core.recog.IStatus;
import com.ai_daily.aitiantian.util.LogUtil;
import com.ai_daily.aitiantian.core.recog.listener.TimeRecorder;
import com.ai_daily.aitiantian.wakeup.MainHandlerConstant;
import com.google.firebase.perf.FirebasePerformance;
import com.google.firebase.perf.metrics.Trace;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.sse.EventSource;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ApiServiceHelper implements IStatus {
    private static final String TAG = "NETWORK";
    private Call<BaseResponseBean> chatCall; //为了可以取消请求
    private EventSource sseEventSource; //为了可以取消请求

    private ApiService getAIP() {
        return new ApiClient().service();
    }

    private void postActive(Handler handler, DeviceInfoParam param) {
        Call<BaseResponseBean> call = getAIP().active(param);
        call.enqueue(new Callback<BaseResponseBean>() {
            @Override
            public void onResponse(Call<BaseResponseBean> call, Response<BaseResponseBean> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "Code = " + response.body().getCode());
                    Log.d(TAG, "data = " + response.body().getData());
                    Log.d(TAG, "message" + response.body().getMessage());

                }
            }

            @Override
            public void onFailure(Call<BaseResponseBean> call, Throwable t) {
                Log.d(TAG, "postChat OnFailure " + t.getMessage());
            }
        });
    }

    public void postChat(Handler handler, ChatParam chatParam) {
        cancelChat();
        chatCall = getAIP().chat(chatParam);
        chatCall.enqueue(new Callback<BaseResponseBean>() {
            @Override
            public void onResponse(Call<BaseResponseBean> call, Response<BaseResponseBean> response) {
                Log.d(TAG, response.toString());
                if (response.isSuccessful()) {
                    Message msg = Message.obtain();
                    switch (response.body().getCode()) {
                        case 200://获取答案成功
                            msg.what = STATUS_PLAY_RESULT;
                            if (response.body().getData() == null) {
                                msg.obj = "请求异常，返回信息为NULL";
                            } else {
                                msg.obj = response.body().getData();
                                Log.d(TAG, "onResponse: " + msg.obj.toString());
                            }
                            break;
                        case 10011://设备禁用
                        case 10012://设备到期
                            msg.what = STATUS_QUERY_INFO;
                            break;
                        default:
                            getErrorMessage(msg, response);
                            break;
                    }

                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onFailure(Call<BaseResponseBean> call, Throwable t) {
                Log.d(TAG, "postChat OnFailure " + t.getMessage());
                if (call.isCanceled()) {
                    return;
                }
                Message msg = Message.obtain();

                msg.what = STATUS_PLAY_RESULT;
                if (BuildConfig.DEBUG) {
                    msg.obj = "请求异常，postChat OnFailure " + t.getMessage();

                } else {
                    msg.obj = Constants.PLEASE_WAIT_TEXT;
                }

                handler.sendMessage(msg);
            }
        });
    }

    public void postChatV3(Handler handler, ChatParam chatParam) {
        // 记录网络请求开始时间
        TimeRecorder.setNetworkRequestStartTime(System.currentTimeMillis());

        // 创建自定义跟踪
        Trace chatTrace = FirebasePerformance.getInstance().newTrace("chat_interaction");
        chatTrace.start();

        // 记录语音识别到请求开始的延迟（转换为秒）
        double timeToRequest = (TimeRecorder.getNetworkRequestStartTime() - 
                TimeRecorder.getVoiceRecognitionEndTime()) / 1000.0;
        chatTrace.putMetric("voice_to_request_delay", (long)(timeToRequest * 1000)); // Firebase需要long类型

        MediaType mediaType = MediaType.parse("application/json");
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("androidId", chatParam.getAndroidId());
        requestMap.put("question", chatParam.getQuestion());
        RequestBody body = RequestBody.create(mediaType, new Gson().toJson(requestMap));
        Request request = new Request.Builder()
                .url("http://tiantianai.ai-daily.com.cn/aiChat/chat_v3")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();

        OkHttpClient okHttpClient = new OkHttpModule().provideStreamOkHttp();
        okhttp3.Call call = okHttpClient.newCall(request);
        final long[] startTime = {System.currentTimeMillis()};
        final boolean[] firstChunkReceived = {false}; // 用于追踪是否已收到第一个数据块
        
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onResponse(@NonNull okhttp3.Call call, @NonNull okhttp3.Response response) throws IOException {
                try {
                    Log.d(TAG, response.toString());
                    if (response.isSuccessful()) {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(response.body().byteStream()));
                        String line;
                        Gson gson = new Gson();

                        // 读取数据流
                        while ((line = reader.readLine()) != null) {
                            // 检查是否包含 "data:" 前缀
                            if (line.startsWith("data:")) {
                                // 只在第一个数据块时记录延迟指标
                                if (!firstChunkReceived[0]) {
                                    firstChunkReceived[0] = true;
                                    
                                    // 计算从语音识别结束到收到首个响应的总延迟（转换为秒）
                                    double voiceToResponseDelay = (System.currentTimeMillis() - 
                                            TimeRecorder.getVoiceRecognitionEndTime()) / 1000.0;
                                    chatTrace.putMetric("voice_to_response_delay", (long)(voiceToResponseDelay * 1000));

                                    // 计算从发起请求到收到首个响应的延迟（转换为秒）
                                    double requestToResponseDelay = (System.currentTimeMillis() - 
                                            TimeRecorder.getNetworkRequestStartTime()) / 1000.0;
                                    chatTrace.putMetric("request_to_first_response_delay", (long)(requestToResponseDelay * 1000));
                                }

                                // 去除 "data:" 前缀
                                String json = line.substring(5).trim();

                                try {
                                    // 解析 JSON 数据
                                    ChatStreamResponse chatStreamResponse = gson.fromJson(json, ChatStreamResponse.class);
                                    if (chatStreamResponse == null) {
                                        continue;
                                    }
                                    String content = chatStreamResponse.getAnswer();
                                    // 更新UI
                                    if (!TextUtils.isEmpty(content)) {
                                        // 切换到主线程更新 UI
                                        handler.post(() -> {
                                            Message msg = Message.obtain();
                                            msg.what = STATUS_PLAY_RESULT;
                                            msg.obj = content;
                                            handler.sendMessage(msg);
                                            long currentTimeMillis = System.currentTimeMillis();
                                            Log.d(TAG, "发送消息：" + content + "\n" + "耗时：" + (currentTimeMillis - startTime[0]) + "ms");
                                            startTime[0] = currentTimeMillis;
                                        });
                                    }
                                } catch (JsonSyntaxException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                } finally {
                    // 停止并上传跟踪数据
                    chatTrace.stop();
                }
            }

            @Override
            public void onFailure(@NonNull okhttp3.Call call, @NonNull IOException e) {
                try {
                    Log.e(TAG, e.getMessage());
                    e.printStackTrace();
                } finally {
                    // 失败时也要停止并上传跟踪数据
                    chatTrace.stop();
                }
            }
        });
    }

    public void cancelChat() {
        if (chatCall != null && !chatCall.isCanceled()) {
            chatCall.cancel();
        }
        if (sseEventSource != null) {
            sseEventSource.cancel();
        }
    }

    public void postInit(Handler handler, DeviceInfoParam param) {
        Call<BaseResponseBean<InitResponseBean>> call = getAIP().init(param);

        CallbackWithRetry callbackWithRetry = new CallbackWithRetry() {
            @Override
            public void retryFailure() {
                Message msg = Message.obtain();
                msg.what = MainHandlerConstant.REQUEST_INIT_FAILURE_CODE;
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) {
                if (response.isSuccessful()) {
                    Message msg = Message.obtain();
                    msg.what = MainHandlerConstant.REQUEST_INIT_SUCCESS_CODE;
                    handler.sendMessage(msg);
                }
            }
        };
        call.enqueue(new Callback<BaseResponseBean<InitResponseBean>>() {
            @Override
            public void onResponse(Call<BaseResponseBean<InitResponseBean>> call, Response<BaseResponseBean<InitResponseBean>> response) {
                LogUtil.d(TAG, response.toString());
                if (response.isSuccessful()) {
                    Log.d(TAG, "Code = " + response.body().getCode());
                    Log.d(TAG, "data = " + response.body().getData());
                    Log.d(TAG, "message" + response.body().getMessage());
                    Message msg = Message.obtain();
                    msg.what = MainHandlerConstant.REQUEST_INIT_SUCCESS_CODE;
                    msg.obj = response.body().getData();
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onFailure(Call<BaseResponseBean<InitResponseBean>> call, Throwable t) {
                callbackWithRetry.onFailure(call, t);
            }
        });


    }

    public void postQueryCommonConfig(Handler handler, CommonConfigParam param) {
        Call<BaseResponseBean<CommonConfigResponseBean>> call = getAIP().queryCommonConfig(param);
        call.enqueue(new Callback<BaseResponseBean<CommonConfigResponseBean>>() {
            @Override
            public void onResponse(Call<BaseResponseBean<CommonConfigResponseBean>> call, Response<BaseResponseBean<CommonConfigResponseBean>> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, response.toString());
                    Message msg = Message.obtain();
                    switch (response.body().getCode()) {
                        case 200://获取答案成功
                            msg.what = STATUS_SHOW_EXPIRE;
                            if (response.body().getData() == null) {
                                msg.obj = "请求异常，返回信息为NULL";
                            } else {
                                msg.obj = response.body().getData();
                            }
                            break;
                        default:
                            getErrorMessage(msg, response);
//                            msg.what = STATUS_PLAY_RESULT;
//                            msg.obj = "请求异常，core = " + response.body().getCode() + " Message = " + response.body().getData();
                            break;
                    }

                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onFailure(Call<BaseResponseBean<CommonConfigResponseBean>> call, Throwable t) {
                Log.d(TAG, "postChat OnFailure " + t.getMessage());
            }
        });
    }

    int a = 0;

    public void postQueryInfo(Handler handler, QueryInfoParam param) {
        Call<BaseResponseBean<QueryInfoResponseBean>> call = getAIP().queryInfo(param);
        call.enqueue(new Callback<BaseResponseBean<QueryInfoResponseBean>>() {
            @Override
            public void onResponse(Call<BaseResponseBean<QueryInfoResponseBean>> call, Response<BaseResponseBean<QueryInfoResponseBean>> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, response.toString());
                    Message msg = Message.obtain();
                    switch (response.body().getCode()) {
                        case 200://获取成功
                            //添加去除设备过期信息
                            msg.what = STATUS_SHOW_NO_EXPIRE;
                            break;
                        case 10011://设备禁用
                        case 10012://设备过期
                            msg.what = STATUS_QUERY_COMMON_CONFIG;
                            break;

                        default:
                            getErrorMessage(msg, response);
//                            msg.what = STATUS_PLAY_RESULT;
//                            msg.obj = "请求异常，core = "+response.body().getCode()+" Message = "+response.body().getData();
                            break;
                    }

                    handler.sendMessage(msg);

                }
            }

            @Override
            public void onFailure(Call<BaseResponseBean<QueryInfoResponseBean>> call, Throwable t) {
                Log.d(TAG, "postChat OnFailure " + t.getMessage());
            }
        });
    }

    public void postQueryLogo(Handler handler, QueryLogoParam param) {
        Call<BaseResponseBean> call = getAIP().queryLogo(param);
        call.enqueue(new Callback<BaseResponseBean>() {
            @Override
            public void onResponse(Call<BaseResponseBean> call, Response<BaseResponseBean> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "Code = " + response.body().getCode());
                    Log.d(TAG, "data = " + response.body().getData());
                    Log.d(TAG, "message" + response.body().getMessage());
                    Message msg = Message.obtain();
                    switch (response.body().getCode()) {
                        case 200://获取成功
                            msg.what = STATUS_UPDATE_LOGO;
                            msg.obj = response.body().getData();
                            break;
                        case 10011://设备禁用
                        case 10012://设备过期

                            break;

                        default:
                            getErrorMessage(msg, response);

                            break;
                    }

                    handler.sendMessage(msg);

                }
            }

            @Override
            public void onFailure(Call<BaseResponseBean> call, Throwable t) {
                Log.d(TAG, "postQueryLogo OnFailure " + t.getMessage());
            }
        });
    }

    private Message getErrorMessage(Message message, Response<? extends
            BaseResponseBean> response) {
        message.what = STATUS_PLAY_RESULT;
        if (BuildConfig.DEBUG) {
            message.obj = "请求异常，core = " + response.body().getCode() + " Message = " + response.body().getData();
        } else {
            message.obj = Constants.PLEASE_WAIT_TEXT;
        }
        return message;
    }


    public void postQueryVersionInfo(Handler handler, QueryVersionInfoParam param) {
        Call<BaseResponseBean<QueryVersionInfoResponseBean>> call = getAIP().queryVersionInfo(param);
        call.enqueue(new Callback<BaseResponseBean<QueryVersionInfoResponseBean>>() {
            @Override
            public void onResponse(Call<BaseResponseBean<QueryVersionInfoResponseBean>> call, Response<BaseResponseBean<QueryVersionInfoResponseBean>> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "Code = " + response.body().getCode());
                    Log.d(TAG, "data = " + response.body().getData());
                    Log.d(TAG, "message" + response.body().getMessage());
                    Message msg = Message.obtain();
                    switch (response.body().getCode()) {
                        case 200://获取成功
                            msg.what = MainHandlerConstant.REQUEST_QUERY_VERSION_INFO_CODE;
                            msg.obj = response.body().getData();
                            break;

                        default:
                            getErrorMessage(msg, response);
                            break;
                    }

                    handler.sendMessage(msg);

                }
            }

            @Override
            public void onFailure(Call<BaseResponseBean<QueryVersionInfoResponseBean>> call, Throwable t) {
                Log.d(TAG, "postQueryVersionInfo OnFailure " + t.getMessage());
                Message msg = Message.obtain();
                msg.what = MainHandlerConstant.REQUEST_QUERY_VERSION_FAILURE_CODE;
                handler.sendMessage(msg);
            }
        });
    }

    public void getKeywords(int type) {
        Call<BaseResponseBean<List<String>>> call = getAIP().queryKeyword(type);
        call.enqueue(new Callback<BaseResponseBean<List<String>>>() {
            @Override
            public void onResponse(Call<BaseResponseBean<List<String>>> call, Response<BaseResponseBean<List<String>>> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "Code = " + response.body().getCode());
                    Log.d(TAG, "data = " + response.body().getData());
                    Log.d(TAG, "message" + response.body().getMessage());
                    Message msg = Message.obtain();
                    switch (response.body().getCode()) {
                        case 200://获取成功
                            if (type == 1) {
                                //敏感词
                                KeywordRepository.getInstance().setSensitiveWords(response.body().getData());
                            } else if (type == 2) {
                                //休眠词
                                KeywordRepository.getInstance().setSleepWords(response.body().getData());
                            }

                            break;

                        default:
                            getErrorMessage(msg, response);
                            break;
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseResponseBean<List<String>>> call, Throwable t) {
                Log.d(TAG, "getKeywords OnFailure " + t.getMessage());
            }
        });
    }

    public void uploadImage(String question, String hitSensitiveWord, String
            deviceId, String filePath) {
        File file = new File(filePath);
        RequestBody reqFile = RequestBody.create(file, MediaType.get("image/jpeg"));
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), reqFile);

        Call<BaseResponseBean> call = getAIP().uploadImage(question, hitSensitiveWord, deviceId, body);
        call.enqueue(new Callback<BaseResponseBean>() {
            @Override
            public void onResponse(Call<BaseResponseBean> call, Response<BaseResponseBean> response) {
                if (response.isSuccessful()) {
                    Message msg = Message.obtain();
                    Log.d(TAG, "Code = " + response.body().getCode());
                    Log.d(TAG, "data = " + response.body().getData());
                    Log.d(TAG, "message" + response.body().getMessage());
                    switch (response.body().getCode()) {
                        case 200://获取成功
                            Log.d(TAG, "图片上传成功");
                        default:
                            getErrorMessage(msg, response);
                            break;
                    }

                }
            }

            @Override
            public void onFailure(Call<BaseResponseBean> call, Throwable t) {
                Log.d(TAG, "uploadImage OnFailure " + t.getMessage());
            }
        });
    }


    public void postCloseChat(CloseChatParam param) {
        Call<BaseResponseBean> call = getAIP().postCloseChat(param);
        call.enqueue(new Callback<BaseResponseBean>() {
            @Override
            public void onResponse(Call<BaseResponseBean> call, Response<BaseResponseBean> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "Code = " + response.body().getCode());
                    Log.d(TAG, "data = " + response.body().getData());
                    Log.d(TAG, "message" + response.body().getMessage());
                    Message msg = Message.obtain();
                    //获取成功
                    if (response.body().getCode() == 200) {
                        Log.d(TAG, "postCloseChat onResponse " + msg.getData());
                    } else {
                        getErrorMessage(msg, response);
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseResponseBean> call, Throwable t) {
                Log.d(TAG, "postCloseChat OnFailure " + t.getMessage());
            }
        });
    }

}
